﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Telepathy.Protocols;
using Telepathy.Servers;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using Button = UnityEngine.UI.Button;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance = null;

    public Dropdown dropdown;

    public ScrollRect scrollRect;
    public GameObject messageTextPrefab;
    public GameObject texmsgPrefab;
    public Transform viewContent;

    public InputField fieldText;

    public Button sendImgBtn;
    public Button sendBtn;

    ServerManager serverManager;

    public string textMessage = null;

    private void Awake()
    {
        Instance = this;
        serverManager = GetComponent<ServerManager>();
    }
    private void Start()
    {
        sendBtn.onClick.AddListener(OnSendMessage);
        sendImgBtn.onClick.AddListener(OnLoadImg);
    }

    void OnSendMessage()
    {
        try
        {
            string str = fieldText.text;
            if (string.IsNullOrEmpty(str)) return;
            int index = dropdown.value;
            string n = dropdown.options[index].text;
            if (n.Length <= 0) return;
            if (n=="All")
            {
                List<MySession> mySessions = serverManager.loginManager.GetAllClient();
                foreach (var item in mySessions)
                {
                    serverManager.SendMsg(item.connId,str);
                }
            }
            else
            {
                MySession session = serverManager.loginManager.GetClient(n);
                serverManager.SendMsg(session.connId, str);
            }
            fieldText.text = string.Empty;
            scrollRect.verticalScrollbar.value = 0;

            GameObject textobj = Instantiate(messageTextPrefab, viewContent);
            Text text = textobj.GetComponent<Text>();
            text.text = string.Format("服务端->{0}: {1}",n, str);
        }
        catch (Exception)
        {

        }
    }

    public void OnLoadImg()
    {
        OpenFileDialog od = new OpenFileDialog();
        od.Title = "请选择头像图片";
        od.Multiselect = false;
        od.Filter = "图片文件(*.jpg,*.png,*.bmp)|*.jpg;*.png;*.bmp";
        if (od.ShowDialog() == DialogResult.OK)
        {
            int index = dropdown.value;
            string n = dropdown.options[index].text;
            if (n.Length <= 0) return;

            Debug.LogWarning(od.FileName);
            StartCoroutine(GetTexture("file://" + od.FileName, (tex) =>
            {
                byte[] png = tex.EncodeToJPG(50);
                RectClass rect = new RectClass();
                rect.x = 0;
                rect.y = 0;
                rect.width  = tex.width;
                rect.height = tex.height;
                string str = JsonConvert.SerializeObject(rect);
                if (n == "All")
                {
                    List<MySession> mySessions = serverManager.loginManager.GetAllClient();
                    foreach (var item in mySessions)
                    {
                        serverManager.SendMsg(item.connId, str, HeaderType.Content, png);
                    }
                }
                else
                {
                    MySession session = serverManager.loginManager.GetClient(n);
                    serverManager.SendMsg(session.connId, str, HeaderType.Content, png);
                }

                GameObject textobj = Instantiate(texmsgPrefab, viewContent);
                RawImage img = textobj.GetComponent<RawImage>();
                img.texture = tex;
                scrollRect.verticalScrollbar.value = 0;
            }));

            od.Dispose();
        }
    }
    public void OnRecvMessage(string username, MessageBase myMsg)
    {

        byte[] bytes = myMsg.bytes;
        if (bytes.Length > 0)
        {
            GameObject textobj = Instantiate(texmsgPrefab, viewContent);
            RawImage img = textobj.GetComponent<RawImage>();
            RectClass rect = JsonConvert.DeserializeObject<RectClass>(myMsg.text);
            Texture2D tex = new Texture2D(rect.width,rect.height);
            tex.LoadImage(bytes);
            img.texture = tex;
        }
        else
        {
            GameObject textobj = Instantiate(messageTextPrefab, viewContent);
            Text text = textobj.GetComponent<Text>();
            text.text = string.Format("来自{0}消息: {1}", username, myMsg.text);
        }
        scrollRect.verticalScrollbar.value = 0;
    }

    public void AddDropdownOptionData(string idStr)
    {
        Dropdown.OptionData option = new Dropdown.OptionData();
        option.text = idStr;
        dropdown.options.Add(option);
    }

    public void RemoveDropdownOptionData(string idStr)
    {
        for (int i = dropdown.options.Count - 1; i >= 0; i--)
        {
            if (dropdown.options[i].text == idStr)
            {
                dropdown.options.RemoveAt(i);
            }
        }
    }


    IEnumerator GetTexture(string url, UnityAction<Texture2D> callback)
    {
        WWW www = new WWW(url);
        yield return www;
        if (www.isDone && www.error == null)
        {
            Texture2D img = www.texture;
            callback.Invoke(img);
        }
    }
}
